import { compareSync } from 'bcryptjs'
import { PassportStrategy } from '@nestjs/passport'
import { IStrategyOptions, Strategy } from 'passport-local'
import { User } from '../user/entities/user.entity'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { BadRequestException } from '@nestjs/common'

export class LocalStorage extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(User) readonly userRepository: Repository<User>
  ) {
    super({
      usernameField: 'username',
      passwordField: 'password'
    } as IStrategyOptions)
  }

  async validate(username: string, password: string) {
    const user = await this.userRepository.findOne({
      where: {
        username
      }
    })
    // console.log('鉴权');
    // console.log(user)

    if (!user) {
      throw new BadRequestException('用户名不正确')
    }

    if (!compareSync(password, user.password)) {
      throw new BadRequestException('密码不正确')
    }

    return user
  }
}
